import Point = laya.maths.Point
import ProgressBar = Laya.ProgressBar

class Monster extends laya.display.Sprite {
    playIndex: number = 0
    speed: number = 4
    mosterx: number = 1
    life: number = 100
    lifeBar: ProgressBar

    timer: Laya.Timer

    constructor() {
        super()

        Laya.loader.load("res/atlas/comp.atlas", Laya.Handler.create(this, () => {
            this.loaded()
        }), null, Laya.Loader.ATLAS)
    }

    loaded(x: number = 0, y: number = 240): void {
        this.addAnimation()
        this.timer = new Laya.Timer()
        this.timer.loop(100, this, this.addAnimation)

        // 添加血量显示
        this.lifeBar = new ProgressBar("comp/progress.png")
        this.lifeBar.value = this.life/100
        this.lifeBar.width = 60
        this.lifeBar.height = 10
        this.addChild(this.lifeBar)

        this.lifeBar.pos(0, 10)
    }

    addAnimation(): void {
        if (++this.playIndex == 9) {
            this.playIndex = 0
        }

        this.refreshUI(this.playIndex)
    }

    refreshUI(index: number = 0): void {
        this.graphics.clear()
        var pos: laya.maths.Point = this.getAxis(index)
        var texture: Texture = Laya.loader.getRes("images/monster" + this.mosterx.toString() +  "_Spritesheet4x3.png")
        var texEnd: Texture = Texture.create(texture, pos.x, pos.y, 60, 70)

        this.graphics.drawTexture(texEnd, 0, 30, 60, 70)
    }

    // Utils
    getAxis(index: number): laya.maths.Point {
        var res: laya.maths.Point = new laya.maths.Point(0, 0);

        var x: number = Math.floor(index%4)
        var y: number = Math.floor(index/4)

        res.x = x * 60
        res.y = y * 70

        return res
    }

    setWave(wave: number): void {
        this.speed += wave/3.0
    }

    // 精灵运动
    move(): void {
        // 生命值消失的怪物不再移动
        if (this.life == 0) {
            return
        }

        var old: Point = new Point()
        old.x = this.x
        old.y = this.y
        
        this.pos(old.x + this.speed, old.y)
    }

    die(): void {
        this.life = 0
        this.refreshUI(9)
        this.lifeBar.removeSelf()
        this.lifeBar.destroy()
        this.timer.clear(this, this.addAnimation)

        // 播放死亡声音
        SoundPlayer.Instance.playMusicDie()

        // 延迟调用销毁
        Laya.timer.once(2000, this, () => {
            this.removeSelf()
            this.destroy()
        }, null, false)        
    }

    //挨打了
    hitbat(): void {
        if (this.life > 0 && this.life <= 100) {
            this.life -= 1;
        }

        this.updateUI()
    }

    //刷新精灵UI -> 调整血量
    updateUI(): void {
        this.lifeBar.value = this.life/100
    }
}